package com.iwjw.ibatis.generate.util;

import com.iwjw.ibatis.generate.model.GenerateConfig;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author: huangweiwei
 * @email: ihuangweiwei@163.com
 * @created:2016/10/25
 */
public class FileUtil {


    public static void main(String[] args){
        File f = new File(FileUtil.class.getResource("/").getPath());
        System.out.println(f.getPath());
    }


    public static boolean writeXml(String path, String fileName, String code, boolean isOverride) {
        File file = new File(buildXmlPath(path));
        return write(file.getPath() + File.separator + fileName, code, isOverride);
    }

    public static boolean write(String pkg, String fileName, String code, boolean isOverride) {
        File file = new File(buildPath(pkg) + File.separator + fileName);
        return write(file.getPath(), code, isOverride);
    }


    private static boolean write(String path, String code, Boolean isOverride) {
        try {
            File file = new File(path);
            if (file.exists() && isOverride) {
                file.delete();
            }
            file.createNewFile();
            FileWriter fileWritter = new FileWriter(path, true);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write(code);
            bufferWritter.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static String buildPath(String pkg) {
        File f = new File(FileUtil.class.getResource("/").getPath());
        String rootPath = f.getPath();
        String path = rootPath.substring(0, rootPath.indexOf(File.separator + "target")) + File.separator + "src" + File.separator + (GenerateConfig.isTest?"test":"main") + File.separator + "java";
        String[] pkgs = pkg.split("\\.");
        for (String str : pkgs) {
            path += File.separator + str;
        }
        File file = new File(path);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        return file.getPath();
    }

    private static String buildXmlPath(String xmlPath) {
        File f = new File(FileUtil.class.getResource("/").getPath());
        String rootPath = f.getPath();
        String path = rootPath.substring(0, rootPath.indexOf(File.separator + "target")) + File.separator + "src" + File.separator + (GenerateConfig.isTest?"test":"main") + File.separator + "resources";
        File file = new File(path, xmlPath);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        return file.getPath();
    }
}
